<?php

namespace control;
/*
*期初类
*/

class initializationClass extends adIndexClass
{
    private const page = 'initialization';
    private const table = 'subject';
    private const title = '期初';
    public const typeOption = ['asset' => '资产', 'debt' => '负债', 'interests' => '权益', 'cost' => '成本', 'loss' => '损益'];
    public const assitOption = ['客户', '供应商', '员工', '部门', '项目', '存货', '现金流'];
    private bool $isExport = false;//是否导出标志

    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow = ''): string
    {
        //生成查询表单
        $html = '';
        return $this->searchExecute([
                'html'=>$html,
                'type'=>'menu',
                'otherButton'=>'no',
                'option'=>'{fixed:true}'
            ]).<<<eof
<style>
.pageDiv{overflow: auto}
</style>
eof. $this->js();
//        return $this->search($html, 'menu', 'no') . $this->js();
    }

    /*列表-查询条件*/
    public function home($workFlow = '现金')
    {
        //生成查询表单
        $data = [
            "id" => "all",
            "menu" => subjectClass::enterpriseSubjectTab()
        ];
        $data['html'] = $this->homeForm($workFlow);
        $data['pageType'] = 'list';
        return $this->tab($data);
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        $subjectType = '资产类';
        //like查询数组
        $like = array();
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            'type' => $subjectType,
            'level' => 1
        );
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        $page = $this->page(array("table" => self::table, 'pageNum'=>1000,"where" => $where, "order" => "list asc"));
        static::rSet(self::$stid . self::page . 'AssetSql', $page['fullSql']);
        //获取表头
        $tr[] = array("科目编码", "科目名称", "方向", "期初金额", "本年借方累计", "本年贷方累计", "年初金额");
        $url = root . 'control/adIndex.html?cla=subject&fun=home';
        //获取记录
        foreach ($page['array'] as $array) {
            $res = $this->loopSubject($array, $url);
            $tr = array_merge($tr, $res);
        }
        //控件
        $button = $this->button($subjectType);
        //返回
        $json['html'] = $button . "<form name='listForm' class='listPage'>" . space . $this->listTable(array("tr" => $tr, "showSort" => true)) . "</form>" . clear;
        return json_encode($json, 320);
    }


    private function loopSubject($array, $url)
    {
        $tr = [];
        $isExitChild = false;
        if (static::total(array('table' => self::table, 'where' => "pid = '$array[id]'")) > 0) {
            $isExitChild = true;
        }
        $empty = '';
        if ($this->isExport) {
            if ($array['level'] > 1) {
                for ($i = 1; $i < $array['level']; $i++) {
                    $empty .= " ";
                }
            }
            $array['initMoney'] = self::centToYuan($array['initMoney']);
            $array['borrowMoney'] = self::centToYuan($array['borrowMoney']);
            $array['loanMoney'] = self::centToYuan($array['loanMoney']);
            if ($array['direction'] == '借') {
                $yearMoney = $array['loanMoney'] + $array['initMoney'] - $array['borrowMoney'];
            } else {
                $yearMoney = $array['initMoney'] + $array['borrowMoney'] - $array['loanMoney'];
            }
            $tr[] = array($array['code'], $array['name'], $array['direction'], $array['initMoney'], $array['borrowMoney'], $array['loanMoney'], $yearMoney);

            //判断是否有下级分类
        } else {
            if ($array['level'] > 1) {
                for ($i = 1; $i < $array['level']; $i++) {
                    $empty .= "&emsp;";
                }
            }
            $array['initMoney'] = self::centToYuan($array['initMoney']);
            $array['borrowMoney'] = self::centToYuan($array['borrowMoney']);
            $array['loanMoney'] = self::centToYuan($array['loanMoney']);
            if ($isExitChild) {
                //有下级的
                $initMoneyInput = "<span data-id='{$array['id']}' data-pid='{$array['pid']}' data-list='{$array['list']}' data-type='initMoney' data-direction='{$array['direction']}'>{$array['initMoney']}</span>";
                $borrowMoneyInput = "<span data-id='{$array['id']}' data-pid='{$array['pid']}' data-list='{$array['list']}' data-type='borrowMoney' data-direction='{$array['direction']}'>{$array['borrowMoney']}</span>";
                $loanMoneyInput = "<span data-id='{$array['id']}' data-pid='{$array['pid']}' data-list='{$array['list']}' data-type='loanMoney' data-direction='{$array['direction']}'>{$array['loanMoney']}</span>";
            } elseif ($array['numAccount'] == '是' || $array['assistAccount'] == '是') {
                //没有下级的,有辅助核算或数量核算的
                $initMoneyInput = text(array('name' => 'initMoney[]', 'class' => 'text', 'type' => 'number', 'other' => "data-id='{$array['id']}' readOnly data-direction='{$array['direction']}' data-pid='{$array['pid']}'  data-type='initMoney' onclick=\"layer('" . self::page . "','assistInit',{id:'" . $array['id'] . "'})\"", 'value' => $array['initMoney']));
                $borrowMoneyInput = text(array('name' => 'borrowMoney[]', 'type' => 'number', 'other' => "data-id='{$array['id']}'  data-pid='{$array['pid']}' data-direction='{$array['direction']}' readOnly  data-type='borrowMoney' onclick=\"layer('" . self::page . "','assistInit',{id:'" . $array['id'] . "'})\"", 'class' => 'text', 'value' => $array['borrowMoney']));
                $loanMoneyInput = text(array('name' => 'loanMoney[]', 'type' => 'number', 'other' => "data-id='{$array['id']}'  data-pid='{$array['pid']}' data-direction='{$array['direction']}' readOnly data-type='loanMoney' onclick=\"layer('" . self::page . "','assistInit',{id:'" . $array['id'] . "'})\"", 'class' => 'text', 'value' => $array['loanMoney']));
            } else {
                //没有下级的
                $initMoneyInput = text(array('name' => 'initMoney[]', 'class' => 'text', 'type' => 'number', 'other' => "data-id='{$array['id']}'  data-pid='{$array['pid']}' data-direction='{$array['direction']}'  data-type='initMoney'", 'blur' => 'setVal', 'value' => $array['initMoney']));
                $borrowMoneyInput = text(array('name' => 'borrowMoney[]', 'type' => 'number', 'other' => "data-id='{$array['id']}'  data-pid='{$array['pid']}'  data-type='borrowMoney' data-direction='{$array['direction']}'", 'class' => 'text', 'blur' => 'setVal', 'value' => $array['borrowMoney']));
                $loanMoneyInput = text(array('name' => 'loanMoney[]', 'type' => 'number', 'other' => "data-id='{$array['id']}'  data-pid='{$array['pid']}'  data-type='loanMoney' data-direction='{$array['direction']}'", 'class' => 'text', 'blur' => 'setVal', 'value' => $array['loanMoney']));
            }
            if ($array['direction'] == '借') {
                $yearMoney = $array['loanMoney'] + $array['initMoney'] - $array['borrowMoney'];
            } else {
                $yearMoney = $array['initMoney'] + $array['borrowMoney'] - $array['loanMoney'];
            }
            $tr[] = array(
                $empty . $array['code'],
                $empty .componentClass::urlTitle( $array['name'], $url, '科目','hands-url'),
                $array['direction'],
                $initMoneyInput,
                $borrowMoneyInput,
                $loanMoneyInput,
                "<span class='year-money' data-pid='{$array['pid']}' data-id='{$array['id']}' data-list='{$array['list']}' data-direction='{$array['direction']}'>{$yearMoney}</span>"
            );
            //判断是否有下级分类
        }
        if ($isExitChild) {
            $levelTwoRes = find(array('table' => self::table, 'where' => "pid = '$array[id]' order by code"));
            foreach ($levelTwoRes['array'] as $val) {
                $res = $this->loopSubject($val, $url);
                $tr = array_merge($tr, $res);
            }
        }
        return $tr;
    }

    private function loopSubjectDown($array)
    {
        $tr = [];
        $isExitChild = false;
        if (static::total(array('table' => self::table, 'where' => "pid = '$array[id]'")) > 0) {
            $isExitChild = true;
        }
        $empty = '';
        if ($array['level'] > 1) {
            for ($i = 1; $i < $array['level']; $i++) {
                $empty .= ' ';
            }
        }
        $tr[] = array($array['code'], $array['name'], $array['direction'], $array['assistAccount'], '', '', '', '', '');
        //判断是否有下级分类
        if ($isExitChild) {
            $levelTwoRes = find(array('table' => self::table, 'where' => "pid = '$array[id]' order by code"));
            foreach ($levelTwoRes['array'] as $val) {
                $res = $this->loopSubjectDown($val);
                $tr = array_merge($tr, $res);
            }
        }
        return $tr;
    }

    /**
     * 填写辅助核算期初
     * @return bool|string
     */
    public function assistInit(): bool|string
    {
        $id = $this->post('id');
        $subject = query(self::table, "id = '$id'");
        if ($subject['assistAccount'] == '是' && $subject['numAccount'] == '否') {
            //辅助核算但没有数量核算时
            $html = $this->onlyAssistAccount($id);
        } elseif ($subject['assistAccount'] == '是' && $subject['numAccount'] == '是') {
            $html = $this->numAndAssistAccount($id);
        }
        $html = "<div style='padding: 10px' class='layerList' id='assistTable'><form name='initForm'>" . $html . hidden(array('name' => 'subjectId', 'value' => $id)) . "</form></div>" . <<<eof
        <script>
        function addRow(id){
               $.post(root+'control/adIndex.html?cla=initialization&fun=addRow',{id:id},function(res) {
                if (res.warn != 2){
                     msg(res.warn,'error')
                }else{
                    $("#assistTable tbody").append(res.html);
                }
            },'json') 
        }
        </script>
eof;
        $button = "<input type='button' class='button' value='保存' onclick=\"subForm('initForm',root+'control/adIndex.html?cla=initialization&fun=assistInitEdit')\">";
        return $this->layer(array("title" => "辅助核算期初", "height" => 600, "width" => 1100, "html" => $html, "button" => $button));
    }

    /**
     * 数量和辅助核算
     */
    private function numAndAssistAccount($id): string
    {
        $subject = query(self::table, "id = '$id'");
        $assistAccountIds = explode(',', $subject['assistAccountIds']);
        $title = "";
        $n = 0;
        foreach ($assistAccountIds as $val) {
            $n++;
            $title .= "<td rowspan='2' style='vertical-align: middle'>$val</td>";
        }
        $tr = '';
        $result = find(array('table' => 'subject_assist', 'where' => "orderId = '{$subject['id']}' order by list asc"));

        foreach ($result['array'] as $array) {
            $temp = [];
            foreach ($assistAccountIds as $val) {
                switch ($val) {
                    case '客户':
                        $kehu = query('kehu', "khid = '$array[khid]'");
                        $temp[] = componentClass::selectText(array('name' => 'khid[]', 'class' => 'width200', 'title' => $kehu['companyName']?:'客户', 'value' => $array['khid'], 'cla' => 'clientProfile', 'fun' => 'getClient'));
                        break;
                    case '员工':
                        $temp[] = selectMultiple(array('name' => 'staffId[]', 'class' => 'width200', 'value' => $array['staffId'], 'table' => 'staff', 'where' => "state !='离职' order by orderNo asc", 'title' => '员工', 'field' => "concat(orderNo,' ',name) as name,stid", 'sqlId' => 'stid', 'sqlField' => 'name'));
                        break;
                    case '供应商':

                        $temp[] = supplierClass::supplierSelect(['name' => 'supplierId[]', 'textName' => 'supplierName[]', 'value' => $array['supplierId'], 'valueText' => supplierClass::getName($array['supplierId'], false), 'width' => 200, 'fun' => 'getSupplier', 'title' => '供应商']);
                        //selectMultiple(array('name' => 'supplierId[]', 'class' => 'width200', 'value' => $array['supplierId'], 'table' => 'supplier', 'where' => "coid = '" . self::$coid . "' order by code asc", 'field' => "concat(code,' ',name) as name,id", 'title' => '供应商', 'sqlId' => 'id', 'sqlField' => 'name'));
                        break;
                    case '项目':
                        $temp[] = selectMultiple(array('name' => 'projectId[]', 'field' => "concat(orderNo,' ',name) as name,id", 'class' => 'width200', 'value' => $array['projectId'], 'table' => 'project', 'where' => "coid = '" . self::$coid . "' order by orderNo asc", 'title' => '项目', 'sqlId' => 'id', 'sqlField' => 'name'));
                        break;
                    case '存货':
                        $material = query('material', "id = '$array[materialId]'");
                        $temp[] = text(array('name' => 'materialName[]', 'value' => $material['code'] . $material['name'], 'class' => 'text width200', 'id' => $array['id'])) .
                            hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])) . "<script>$('#{$array['id']}').bigAutocomplete({
                        // width:543,
                        url:root + 'control/adIndex.html?cla=voucherEdit&fun=getMaterial',
                        callback:function(data,e){
                           $(e).siblings(\"[name='materialId[]']\").val(data.id);
                        }
                    });</script>";
                        break;
                    case '部门':
                        $temp[] = selectMultiple(array('name' => 'departmentId[]', 'class' => 'width200', 'value' => $array['departmentId'], 'table' => 'department', 'where' => "1=1 order by orderNo asc", 'field' => "concat(orderNo,' ',name) as name,id", 'title' => '部门', 'sqlId' => 'id', 'sqlField' => 'name'));
                        break;
                    case '现金流':
                        $temp[] = selectMultiple(array('name' => 'cashId[]', 'class' => 'width200', 'value' => $array['cashId'], 'table' => 'cash', 'where' => "coid = '" . self::$coid . "' order by code asc", 'title' => '现金流', 'sqlId' => 'id', 'field' => "concat(code,' ',name) as name,id", 'sqlField' => 'name'));
                        break;
                }
            }
            $tr .= "<tr>";
            foreach ($temp as $val) {

                $tr .= "<td>" . $val . "</td>";
            }
            $tr .= "<td>" . $subject['numAccountText'] . "</td>
                    <td>" . text(array('name' => 'initNum[]', 'value' => voucherEditClass::formatZero($array['initNum']), 'class' => 'text width100', 'type' => 'number')) . "</td>
                    <td>" . text(array('name' => 'initMoney[]', 'value' => $array['initMoney'], 'class' => 'text width100', 'type' => 'number')) . "</td>
                    <td>" . text(array('name' => 'jieNum[]', 'value' => voucherEditClass::formatZero($array['jieNum']), 'class' => 'text width100', 'type' => 'number')) . "</td>
                    <td>" . text(array('name' => 'jieMoney[]', 'value' => $array['jieMoney'], 'class' => 'text width100', 'type' => 'number')) . "</td>
                    <td>" . text(array('name' => 'daiNum[]', 'value' => voucherEditClass::formatZero($array['daiNum']), 'class' => 'text width100', 'type' => 'number')) . "</td>
                    <td>" . text(array('name' => 'daiMoney[]', 'value' => $array['daiMoney'], 'class' => 'text width100', 'type' => 'number')) . hidden(array('name' => 'mxId[]', 'value' => $array['id'])) . "</td>
                    <td><span class='del-row-button' onclick='decline(this)'>删除</span></td>";
            $tr .= "</tr>";
        }
        $n = $n + 8;
        //辅助核算但没有数量核算时
        return <<<eof
                <table class="tableMany">
                    <thead>
                        <tr>
                            $title
                            <td rowspan="2" style="vertical-align:middle">单位</td>
                            <td colspan="2" class="center">期初余额</td>
                            <td class="center" colspan="2">本年累计借方</td>
                            <td class="center" colspan="2">本年累计贷方</td>
                            <td rowspan="2" style="vertical-align: middle">
                                <span style="display: block;text-align: center;" class='del-row-button' onclick="addRow('{$id}')">添加</span>
                            </td>
                        </tr>
                        <tr style="background-color: #f2f2f2;color: #555;"><td>数量</td><td>金额</td><td>数量</td><td>金额</td><td>数量</td><td>金额</td></tr>
                    </thead>
                    <tbody>
                       $tr
                    </tbody>
                </table>
eof;

    }

    /**
     * 只有辅助核算
     */
    private function onlyAssistAccount($id): string
    {
        $subject = query(self::table, "id = '$id'");
        $assistAccountIds = explode(',', $subject['assistAccountIds']);
        $title = [];
        foreach ($assistAccountIds as $val) {
            $title[] = $val;
        }
        $title = array_merge($title, ['期初余额', '本年累计借方', '本年累计贷方', "<span class='del-row-button' onclick=\"addRow('{$id}')\">添加</span>"]);
        $educationTr[] = $title;

        $result = find(array('table' => 'subject_assist', 'where' => "orderId = '{$subject['id']}' order by list asc"));
        foreach ($result['array'] as $array) {
            $temp = [];
            foreach ($assistAccountIds as $val) {
                switch ($val) {
                    case '客户':
                        $kehu = query('kehu', "khid = '$array[khid]'");
                        $temp[] = componentClass::selectText(array('name' => 'khid[]', 'class' => 'width200', 'title' => $kehu['companyName']?:'客户', 'value' => $array['khid'], 'cla' => 'clientProfile', 'fun' => 'getClient'));
                        break;
                    case '员工':
                        $temp[] = selectMultiple(array('name' => 'staffId[]', 'class' => 'width200', 'value' => $array['staffId'], 'table' => 'staff', 'where' => "state !='离职' order by orderNo asc", 'title' => '员工', 'field' => "concat(orderNo,' ',name) as name,stid", 'sqlId' => 'stid', 'sqlField' => 'name'));
                        break;
                    case '供应商':
                        $temp[] = supplierClass::supplierSelect(['name' => 'supplierId[]', 'textName' => 'supplierName[]', 'width' => 200, 'value' => $array['supplierId'], 'valueText' => supplierClass::getName($array['supplierId'], false), 'fun' => 'getSupplier', 'title' => '供应商']);
                        //selectMultiple(array('name' => 'supplierId[]', 'class' => 'width200', 'value' => $array['supplierId'], 'table' => 'supplier', 'where' => "coid = '" . self::$coid . "' order by code asc", 'field' => "concat(code,' ',name) as name,id", 'title' => '供应商', 'sqlId' => 'id', 'sqlField' => 'name'));
                        break;
                    case '项目':
                        $temp[] = selectMultiple(array('name' => 'projectId[]', 'field' => "concat(orderNo,' ',name) as name,id", 'class' => 'width200', 'value' => $array['projectId'], 'table' => 'project', 'where' => "coid = '" . self::$coid . "' order by orderNo asc", 'title' => '项目', 'sqlId' => 'id', 'sqlField' => 'name'));
                        break;
                    case '存货':
                        $material = query('material', "id = '$array[materialId]'");
                        $temp[] = text(array('name' => 'materialName[]', 'value' => $material['code'] . $material['name'], 'class' => 'text width200', 'id' => $array['id'])) .
                            hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])) . "<script>$('#{$array['id']}').bigAutocomplete({
                        // width:543,
                        url:root + 'control/adIndex.html?cla=voucherEdit&fun=getMaterial',
                        callback:function(data,e){
                           $(e).siblings(\"[name='materialId[]']\").val(data.id);
                        }
                    });</script>";
                        break;
                    case '部门':
                        $temp[] = selectMultiple(array('name' => 'departmentId[]', 'class' => 'width200', 'value' => $array['departmentId'], 'table' => 'department', 'where' => "1=1 order by orderNo asc", 'field' => "concat(orderNo,' ',name) as name,id", 'title' => '部门', 'sqlId' => 'id', 'sqlField' => 'name'));
                        break;
                    case '现金流':
                        $temp[] = selectMultiple(array('name' => 'cashId[]', 'class' => 'width200', 'value' => $array['cashId'], 'table' => 'cash', 'where' => "coid = '" . self::$coid . "' order by code asc", 'title' => '现金流', 'sqlId' => 'id', 'field' => "concat(code,' ',name) as name,id", 'sqlField' => 'name'));
                        break;
                }
            }
            $educationTr[] = array_merge($temp, [
                text(array('name' => 'initMoney[]', 'value' => $array['initMoney'], 'class' => 'text width100', 'type' => 'number')),
                text(array('name' => 'jieMoney[]', 'value' => $array['jieMoney'], 'type' => 'number', 'class' => 'text width100')),
                text(array('name' => 'daiMoney[]', 'value' => $array['daiMoney'], 'type' => 'number', 'class' => 'text width100')) . hidden(array('name' => 'mxId[]', 'value' => $array['id'])),
                "<span class='del-row-button' onclick='decline(this)'>删除</span>"
            ]);
        }
        //辅助核算但没有数量核算时
        return $this->tableMany(array('tr' => $educationTr, 'end' => true));
    }

    /**
     * 辅助核算期初余额保存
     * @return false|string
     */
    public function assistInitEdit()
    {
        $id = $this->post('subjectId');
        $subject = query(self::table, "id = '$id'");
        $mxIds = $this->post('mxId') ?: [];
        $khids = $this->post('khid') ?: [];
        $staffIds = $this->post('staffId') ?: [];
        $supplierIds = $this->post('supplierId') ?: [];
        $projectIds = $this->post('projectId') ?: [];
        $materialIds = $this->post('materialId') ?: [];
        $departmentIds = $this->post('departmentId') ?: [];
        $cashIds = $this->post('cashId') ?: [];
        $initMoneys = $this->post('initMoney') ?: [];
        $jieMoneys = $this->post('jieMoney') ?: [];
        $daiMoneys = $this->post('daiMoney') ?: [];
        $initNums = $this->post('initNum') ?: [];
        $jieNums = $this->post('jieNum') ?: [];
        $daiNums = $this->post('daiNum') ?: [];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '您还没有编辑权限';
        } elseif (empty($subject['id'])) {
            $json['warn'] = '未找到科目';
        } elseif (!static::is_null_array($mxIds) && static::is_null_array($initMoneys) && static::is_null_array($jieMoneys) && static::is_null_array($daiMoneys)) {
            $json['warn'] = '请填写期初余额';
        } else {
            $assistAccountIds = explode(',', $subject['assistAccountIds']);
            $json['warn'] = '';
            $this->startTrans();
            foreach ($mxIds as $k => $mxId) {
                $mx = query('subject_assist', "id = '$mxId'");
                if (in_array('客户', $assistAccountIds) && (!isset($khids[$k]) || empty($khids[$k]))) {
                    $json['warn'] = "第" . ($k + 1) . "行未选择客户";
                    break;
                }
                if (in_array('供应商', $assistAccountIds) && (!isset($supplierIds[$k]) || empty($supplierIds[$k]))) {
                    $json['warn'] = "第" . ($k + 1) . "行未选择供应商";
                    break;
                }
                if (in_array('项目', $assistAccountIds) && (!isset($projectIds[$k]) || empty($projectIds[$k]))) {
                    $json['warn'] = "第" . ($k + 1) . "行未选择项目";
                    break;
                }
                if (in_array('员工', $assistAccountIds) && (!isset($staffIds[$k]) || empty($staffIds[$k]))) {
                    $json['warn'] = "第" . ($k + 1) . "行未选择员工";
                    break;
                }
                if (in_array('存货', $assistAccountIds) && (!isset($materialIds[$k]) || empty($materialIds[$k]))) {
                    $json['warn'] = "第" . ($k + 1) . "行未选择存货";
                    break;
                }
                if (in_array('部门', $assistAccountIds) && (!isset($departmentIds[$k]) || empty($departmentIds[$k]))) {
                    $json['warn'] = "第" . ($k + 1) . "行未选择部门";
                    break;
                }
                if (in_array('现金流', $assistAccountIds) && (!isset($cashIds[$k]) || empty($cashIds[$k]))) {
                    $json['warn'] = "第" . ($k + 1) . "行未选择现金流";
                    break;
                }
                $field = [
                    'khid' => $khids[$k] ?? '',
                    'staffId' => $staffIds[$k] ?? '',
                    'supplierId' => $supplierIds[$k] ?? '',
                    'projectId' => $projectIds[$k] ?? '',
                    'materialId' => $materialIds[$k] ?? '',
                    'departmentId' => $departmentIds[$k] ?? '',
                    'cashId' => $cashIds[$k] ?? '',
                    'initMoney' => $initMoneys[$k] ?? 0,
                    'jieMoney' => $jieMoneys[$k] ?? 0,
                    'daiMoney' => $daiMoneys[$k] ?? 0,
                    'initNum' => voucherEditClass::formatNum($initNums[$k] ?? 0),
                    'jieNum' => voucherEditClass::formatNum($jieNums[$k] ?? 0),
                    'daiNum' => voucherEditClass::formatNum($daiNums[$k] ?? 0),
                ];
                $idCollection = array_filter([$field['khid'], $field['staffId'], $field['supplierId'], $field['projectId'], $field['materialId'], $field['departmentId'], $field['cashId']]);
                asort($idCollection);
                if (empty($mx['id'])) {
                    $field = array_merge($field, [
                        'id' => $mxId,
                        'coid' => self::$coid,
                        'orderId' => $subject['id'],
                        'idCollection' => implode(',', $idCollection)
                    ]);
                    $warn = static::insert(array(
                        'table' => 'subject_assist',
                        'field' => $field
                    ));
                } else {
                    $field['idCollection'] = implode(',', $idCollection);
                    $warn = static::update(array(
                        'table' => 'subject_assist',
                        'field' => $field,
                        'where' => "id = '$mxId'"
                    ));
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = "保存失败";
                    break;
                }
            }
            $bool = update(array('table' => self::table, 'field' => ['initMoney' => self::yuanToCent(array_sum($initMoneys)), 'borrowMoney' => self::yuanToCent(array_sum($jieMoneys)), 'loanMoney' => self::yuanToCent(array_sum($daiMoneys)),], 'where' => "id = '$subject[id]'"));
            if ($bool != '更新成功') {
                $json['warn'] = '保存失败';
            }
            if (empty($json['warn'])) {
                foreach (['initMoney', 'borrowMoney', 'loanMoney'] as $fieldName) {
                    $this->loopMoney($subject['pid'], $fieldName);
                }
                $json['warn'] = 2;
                $_SESSION['warn'] = '保存成功';
                $this->commitTrans();
                delete(array('table' => 'subject_assist', 'where' => "orderId = '$subject[id]' and id not in ('" . implode("','", $mxIds) . "')"));
            } else {
                $this->rollback();
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 添加一行
     */
    public function addRow()
    {
        $id = $this->post('id');
        $subject = query(self::table, "id = '$id'");
        if (empty($subject['id'])) {
            $json['warn'] = '未找到科目';
        } else {
            $json['warn'] = 2;
            $assistAccountIds = explode(',', $subject['assistAccountIds']);
            if ($subject['assistAccount'] == '是' && $subject['numAccount'] == '否') {
                $temp = [];
                $mxId = suiji();
                foreach ($assistAccountIds as $val) {

                    switch ($val) {
                        case '客户':
                            $temp[] = componentClass::selectText(array('name' => 'khid[]', 'class' => 'width200', 'cla' => 'clientProfile', 'fun' => 'getClient', 'title' => '客户'));
                            break;
                        case '员工':
                            $temp[] = selectMultiple(array('name' => 'staffId[]', 'class' => 'width200', 'table' => 'staff', 'where' => "state !='离职' order by orderNo asc", 'title' => '员工', 'field' => "concat(orderNo,' ',name) as name,stid", 'sqlId' => 'stid', 'sqlField' => 'name'));
                            break;
                        case '供应商':
                            $temp[] = supplierClass::supplierSelect(['name' => 'supplierId[]', 'textName' => 'supplierName[]', 'width' => 200, 'fun' => 'getSupplier', 'title' => '供应商']);
//                                selectMultiple(array('name' => 'supplierId[]', 'class' => 'width200', 'table' => 'supplier', 'where' => "coid = '" . self::$coid . "' order by code asc", 'field' => "concat(code,' ',name) as name,id", 'title' => '供应商', 'sqlId' => 'id', 'sqlField' => 'name'));
                            break;
                        case '项目':
                            $temp[] = selectMultiple(array('name' => 'projectId[]', 'class' => 'width200', 'table' => 'project', 'field' => "concat(orderNo,' ',name) as name,id", 'where' => "coid = '" . self::$coid . "' order by orderNo asc", 'title' => '项目', 'sqlId' => 'id', 'sqlField' => 'name'));
                            break;
                        case '存货':
                            $temp[] = text(array('name' => 'materialName[]', 'value' => '', 'class' => 'text width200', 'id' => $mxId)) .
                                hidden(array('name' => 'materialId[]', 'value' => '')) . "<script>$('#{$mxId}').bigAutocomplete({
                                // width:543,
                                url:root + 'control/adIndex.html?cla=voucherEdit&fun=getMaterial',
                                callback:function(data,e){
                                   $(e).siblings(\"[name='materialId[]']\").val(data.id);
                                }
                            });</script>";
                            break;
                        case '部门':
                            $temp[] = selectMultiple(array('name' => 'departmentId[]', 'class' => 'width200', 'table' => 'department', 'where' => "1=1 order by orderNo asc", 'title' => '部门', 'sqlId' => 'id', 'field' => "concat(orderNo,' ',name) as name,id", 'sqlField' => 'name'));
                            break;
                        case '现金流':
                            $temp[] = selectMultiple(array('name' => 'cashId[]', 'class' => 'width200', 'table' => 'cash', 'where' => "coid = '" . self::$coid . "' order by code asc", 'title' => '现金流', 'field' => "concat(code,' ',name) as name,id", 'sqlId' => 'id', 'sqlField' => 'name'));
                            break;
                    }
                }
                $educationTr = array_merge($temp, [
                    text(array('name' => 'initMoney[]', 'class' => 'text width100', 'type' => 'number')),
                    text(array('name' => 'jieMoney[]', 'type' => 'number', 'class' => 'text width100')),
                    text(array('name' => 'daiMoney[]', 'type' => 'number', 'class' => 'text width100')) . hidden(array('name' => 'mxId[]', 'value' => $mxId)),
                ]);
                $json['html'] = '<tr>';
                foreach ($educationTr as $value) {
                    $json['html'] .= "<td>" . $value . "</td>";
                }
                $json['html'] .= "<td><span class='del-row-button' onclick='decline(this)'>删除</span></td></tr>";
            } elseif ($subject['assistAccount'] == '是' && $subject['numAccount'] == '是') {
                $title = "";
                foreach ($assistAccountIds as $val) {
                    $title .= "<td rowspan='2' style='vertical-align: middle'>$val</td>";
                }
                $tr = '';
                $temp = [];
                $mxId = suiji();
                foreach ($assistAccountIds as $val) {
                    switch ($val) {
                        case '客户':
                            $temp[] = selectMultiple(array('name' => 'khid[]', 'class' => 'width200', 'table' => 'kehu', 'where' => "coid = '" . self::$coid . "' order by time asc", 'title' => '客户', 'sqlId' => 'khid', 'sqlField' => 'companyName'));
                            break;
                        case '员工':
                            $temp[] = selectMultiple(array('name' => 'staffId[]', 'class' => 'width200', 'table' => 'staff', 'where' => "state !='离职' order by time asc", 'title' => '员工', 'sqlId' => 'stid', 'sqlField' => 'name'));
                            break;
                        case '供应商':
                            $temp[] = supplierClass::supplierSelect(['name' => 'supplierId[]', 'textName' => 'supplierName[]', 'width' => 200, 'fun' => 'getSupplier', 'title' => '供应商']);
//                            $temp[] = selectMultiple(array('name' => 'supplierId[]', 'class' => 'width200', 'table' => 'supplier', 'where' => "coid = '" . self::$coid . "' order by time asc", 'title' => '供应商', 'sqlId' => 'id', 'sqlField' => 'name'));
                            break;
                        case '项目':
                            $temp[] = selectMultiple(array('name' => 'projectId[]', 'class' => 'width200', 'table' => 'project', 'where' => "coid = '" . self::$coid . "' order by time asc", 'title' => '项目', 'sqlId' => 'id', 'sqlField' => 'name'));
                            break;
                        case '存货':
                            $temp[] = text(array('name' => 'materialName[]', 'class' => 'text width200', 'id' => $mxId)) .
                                hidden(array('name' => 'materialId[]', 'value' => '')) . "<script>$('#{$mxId}').bigAutocomplete({
                        // width:543,
                        url:root + 'control/adIndex.html?cla=voucherEdit&fun=getMaterial',
                        callback:function(data,e){
                           $(e).siblings(\"[name='materialId[]']\").val(data.id);
                        }
                    });</script>";
                            break;
                        case '部门':
                            $temp[] = selectMultiple(array('name' => 'departmentId[]', 'class' => 'width200', 'table' => 'department', 'where' => "1=1 order by time asc", 'title' => '部门', 'sqlId' => 'id', 'sqlField' => 'name'));
                            break;
                        case '现金流':
                            $temp[] = selectMultiple(array('name' => 'cashId[]', 'class' => 'width200', 'table' => 'cash', 'where' => "coid = '" . self::$coid . "' order by time asc", 'title' => '现金流', 'sqlId' => 'id', 'sqlField' => 'name'));
                            break;
                    }
                }
                foreach ($temp as $val) {
                    $tr .= "<td>" . $val . "</td>";
                }
                $json['html'] = "<tr>" . $tr . "
            <td>" . $subject['numAccountText'] . "</td>
            <td>" . text(array('name' => 'initNum[]', 'class' => 'text width100', 'type' => 'number')) . "</td>
            <td>" . text(array('name' => 'initMoney[]', 'class' => 'text width100', 'type' => 'number')) . "</td>
            <td>" . text(array('name' => 'jieNum[]', 'class' => 'text width100', 'type' => 'number')) . "</td>
            <td>" . text(array('name' => 'jieMoney[]', 'class' => 'text width100', 'type' => 'number')) . "</td>
            <td>" . text(array('name' => 'daiNum[]', 'class' => 'text width100', 'type' => 'number')) . "</td>
            <td>" . text(array('name' => 'daiMoney[]', 'class' => 'text width100', 'type' => 'number')) . hidden(array('name' => 'mxId[]', 'value' => $mxId)) . "</td>
            <td><span class='del-row-button' onclick='decline(this)'>删除</span></td></tr>
            ";
            }
        }
        return json_encode($json, 320);
    }

    /**
     *
     * @return string|void
     */
    private function js()
    {
        $page = self::page;
        return <<<eof
<script>

function setVal(e){
    let money = e.value;
    let id = $(e).data('id');
    let type = $(e).data('type');
    $.post(root+'control/adIndex.html?cla={$page}&fun=setVal',{money:money,id:id,type:type},function(res) {
        if (res.warn != 2){
             msg(res.warn,'error')
        }else{
             let pid = $(e).data('pid');
             let direction = $(e).data('direction');
             
            $(e).parent().parent().find(".year-money").html((res.data.money).toFixed(2));
            calculateMoney(pid,type)
        }
    },'json')
}
 function calculateMoney(pid,classify){
    $(".fixed-thead-body [data-id='"+pid+"'][data-type='"+classify+"']").each(function() {
      let parentId = $(this).data('pid');
      let type = $(this).data('type');
      let id = $(this).data('id');
      let money = 0;
      let direction = $(this).data('direction');
      $(".fixed-thead-body [data-pid = '"+id+"'][data-type='"+type+"']").each(function (){
          if (classify == 'initMoney'){
              if ($(this).is("input")){
                  if ((direction =='借' && $(this).data('direction') =='借') || (direction =='贷' && $(this).data('direction') =='贷')){
                       money+=Number($(this).val())
                  }else{
                      money-=Number($(this).val())
                  }
              }else{
                  if ((direction =='借' && $(this).data('direction') =='借') || (direction =='贷' && $(this).data('direction') =='贷')){
                      money+=Number($(this).text())
                  }else{
                      money-=Number($(this).text())
                  }
              }
          }else{
              if ($(this).is("input")){
                  money+=Number($(this).val())
              }else{
                  money+=Number($(this).text())
              }
          }
      })
      $(this).text(money.toFixed(2));
       let yearMoney = 0;
      $(".fixed-thead-body .year-money[data-pid = '"+id+"']").each(function (){
          if ((direction =='借' && $(this).data('direction') =='借') || (direction =='贷' && $(this).data('direction') =='贷')){
                  yearMoney+=Number($(this).text())
              }else{
                  yearMoney-=Number($(this).text())
              }
      })
      $(this).parent().parent().find(".year-money").html(yearMoney.toFixed(2));
      if (parentId && parentId !=='undefined'){
          calculateMoney(parentId,type,direction)
      }
    })        
}
</script>
eof;
    }


    public function setVal()
    {
        $id = $this->post('id');
        $fieldName = $this->post('type');
        $money = $this->post('money');
        $field = [
            $fieldName => $money,
        ];
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(array('table' => 'checkout', 'where' => "coid = '" . self::$coid . "'")) > 0) {
            $json['warn'] = '已存在结账，不能修改';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此科目';
        } elseif (empty($fieldName)) {
            $json['warn'] = '未找到类型';
        } elseif (!empty($money) && preg_match(checkPrice, abs($money)) == 0) {
            $json['warn'] = '金额格式错误';
        } else {
            $field[$fieldName] = self::yuanToCent($money);
            $json['warn'] = static::update([
                "table" => self::table,
                "field" => $field,
                "where" => $where
            ]);

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $name = match ($fieldName) {
                    'initMoney' => '期初金额',
                    'borrowMoney' => '借方累计',
                    'loanMoney' => '贷方累计',
                    default => '未找到类型',
                };
                $this->loopMoney($info['pid'], $fieldName);
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】的' . $name . '为：' . $money;
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $json['warn'] = 2;
                $info = query(self::table, "id = '$id'");
                if ($info['direction'] == '借') {
                    $json['data']['money'] = self::centToYuan($info['initMoney']) + self::centToYuan($info['loanMoney']) - self::centToYuan($info['borrowMoney']);
                } else {
                    $json['data']['money'] = self::centToYuan($info['initMoney']) - self::centToYuan($info['loanMoney']) + self::centToYuan($info['borrowMoney']);
                }

            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 计算父级的金额
     */
    public function loopMoney($pid, $type)
    {
        $info = query(self::table, "id = '$pid'");
        if (!empty($info['id'])) {
            $jieMoney = find(array('table' => self::table, 'where' => "pid = '$info[id]' and direction = '借'", 'sum' => $type));
            $daiMoney = find(array('table' => self::table, 'where' => "pid = '$info[id]' and direction = '贷'", 'sum' => $type));
            if ($type == 'initMoney') {
                if ($info['direction'] == '借') {
                    $money = $jieMoney - $daiMoney;
                } else {
                    $money = $daiMoney - $jieMoney;
                }
            } else {
                $money = $jieMoney + $daiMoney;
            }
            update(array('table' => self::table, 'field' => [$type => $money], 'where' => "id = '$info[id]'"));
            if ($info['pid'] != '0') {
                $this->loopMoney($info['pid'], $type);
            }
        }
    }

    /**
     * 操作按钮
     * @param $subjectType
     * @return string
     */
    private function button($subjectType): string
    {
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','equilibrium',{})\" class='spanButton'>试算平衡</span>\n";
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData&type=" . $subjectType . "'><span class='spanButton'>导出</span></a>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','reset',{})\" class='spanButton'>重置</span>\n";
        }
        return "<div class='flex-box m-t-10'>".$button."</div>";
    }

    /**
     * 重置
     * @return string
     */
    public function reset(): string
    {
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "提示：" => "是否确认重置期初",
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => "提示", "height" => 200, "width" => 600, "html" => $html));
    }

    /**
     * 重置
     */
    public function resetEdit()
    {
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = "您还没有编辑的权限";
        } else {
            $this->startTrans();
            $warn = update(array('table' => self::table, 'field' => ['initMoney' => 0, 'borrowMoney' => 0, 'loanMoney' => 0], 'where' => "coid = '" . self::$coid . "'"));
            $bool = delete(array('table' => 'subject_assist', 'where' => "coid = '" . self::$coid . "'"));
            if ($warn == '更新成功' && $bool == '删除成功') {
                $this->commitTrans();
                $json['warn'] = 2;
                $_SESSION['warn'] = '重置成功';
                $text = $this->control['name'] . "重置了期初";
                $this->logText(array("type" => self::page, "text" => $text));
            } else {
                $this->rollback();
                $json['warn'] = '重置失败';
            }

        }
        return json_encode($json, 320);
    }

    /**
     * 试算平衡
     *
     * 全部账户的借方期初余额合计数=全部账户的贷方期初余额合计数；
     * 全部账户的借方发生额合计=全部账户的贷方发生额合计；
     * 全部账户的借方期末余额合计=全部账户的贷方期末余额合计。
     *
     */
    public function equilibrium(): bool|string
    {
        $jieMoney = find(array('table' => self::table, 'where' => "direction = '借' and level = 1 and coid = '" . self::$coid . "'", 'sum' => "initMoney"));
        $daiMoney = find(array('table' => self::table, 'where' => "direction = '贷' and level = 1 and coid = '" . self::$coid . "'", 'sum' => "initMoney"));
        $warn = "平衡";
        $initSrc = $sumSrc = imgSrc('img/control/balance_center.svg');
        if ($jieMoney != $daiMoney) {
            $warn = '不平衡';
            $initSrc = $jieMoney > $daiMoney ? imgSrc('img/control/balance_left.svg') : imgSrc('img/control/balance_right.svg');
        }
        $jieMoney = self::centToYuan($jieMoney);
        $daiMoney = self::centToYuan($daiMoney);
        $initBalance = $jieMoney - $daiMoney;
        $borrowMoney = find(array('table' => self::table, 'where' => "level = 1 and coid = '" . self::$coid . "'", 'sum' => "borrowMoney"));
        $loanMoney = find(array('table' => self::table, 'where' => "level = 1 and coid = '" . self::$coid . "'", 'sum' => "loanMoney"));
        if ($borrowMoney != $loanMoney) {
            $warn = '不平衡';
            $sumSrc = $borrowMoney > $loanMoney ? imgSrc('img/control/balance_left.svg') : imgSrc('img/control/balance_right.svg');
        }
        $borrowMoney = self::centToYuan($borrowMoney);
        $loanMoney = self::centToYuan($loanMoney);
        $balanceMoney = $borrowMoney - $loanMoney;
        $html = <<<eof
<div style="text-align: center;padding: 10px">
    <div style="display: flex;flex-direction: row;justify-content: space-around">
         <div style="width: 200px">
            <div>期初余额</div>
            <img src="$initSrc"/>
            <div style="padding: 5px"><span style="float: left">借</span><span>&nbsp;</span><span style="float: right">贷</span></div>
            <div style="padding: 5px 0"><span style="float: left">$jieMoney</span><span>$initBalance</span><span style="float: right">$daiMoney</span></div>
        </div>
        <div style="width: 200px">
            <div>累计发生</div>
            <img src="$sumSrc"/>
            <div style="padding: 5px"><span style="float: left">借</span><span>&nbsp;</span><span style="float: right">贷</span></div>
            <div style="padding: 5px 0"><span style="float: left">$borrowMoney</span><span>$balanceMoney</span><span style="float: right">$loanMoney</span></div>
        </div>
    </div>
    <div style="margin: 10px;font-size: 15px">$warn</div>
</div>
eof;

        //返回
        return $this->layer(array("title" => "提示", "height" => 340, "width" => 700, "html" => $html));

    }

    public function loss()
    {
        $json['html'] = $this->homeForm('损益');
        return json_encode($json, 320);
    }

    public function lossSearch()
    {
        $subjectType = '损益类';
        //like查询数组
        $like = array(
            "name" => $this->post('name'),
            "code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            'type' => $subjectType,
            'level' => 1,
        );
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        $page = $this->page(array("table" => self::table,'pageNum'=>1000, "where" => $where, "order" => "list asc"));
        static::rSet(self::$stid . self::page . 'lossSql', $page['fullSql']);
        //获取表头
        $tr[] = array("科目编码", "科目名称", "方向", "期初金额", "借方累计", "贷方累计", "年初金额");
        $url = root . 'control/adIndex.html?cla=subject&fun=home&menu=loss';
        //获取记录
        foreach ($page['array'] as $array) {
            $res = $this->loopSubject($array, $url);
            $tr = array_merge($tr, $res);
        }
        //控件
        $button = $this->button($subjectType);
        //返回
        $json['html'] = $button . "<form name='lossForm' class='listPage'>" . space . $this->listTable(array("tr" => $tr, "showSort" => true)) . "</form>" . clear;
        return json_encode($json, 320);
    }

    public function cost()
    {
        $json['html'] = $this->homeForm('成本');
        return json_encode($json, 320);
    }

    public function costSearch()
    {
        $subjectType = '成本类';
        //like查询数组
        $like = array(
            "name" => $this->post('name'),
            "code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            'type' => $subjectType,
            'level' => 1,
        );
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        $page = $this->page(array("table" => self::table,'pageNum'=>1000, "where" => $where, "order" => "list asc"));
        static::rSet(self::$stid . self::page . 'costSql', $page['fullSql']);
        //获取表头
        $tr[] = array("科目编码", "科目名称", "方向", "期初金额", "借方累计", "贷方累计", "年初金额");
        $url = root . 'control/adIndex.html?cla=subject&fun=home&menu=cost';
        //获取记录
        foreach ($page['array'] as $array) {
            $res = $this->loopSubject($array, $url);
            $tr = array_merge($tr, $res);
        }
        //控件
        $button = $this->button($subjectType);
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='costForm' class='listPage'>" . space . $this->listTable(array("tr" => $tr, "showSort" => true)) . "</form>" .  clear;
        return json_encode($json, 320);
    }

    public function interests()
    {
        $json['html'] = $this->homeForm('权益');
        return json_encode($json, 320);
    }

    public function interestsSearch()
    {
        $subjectType = '权益类';
        //like查询数组
        $like = array(
            "name" => $this->post('name'),
            "code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            'type' => $subjectType,
            'level' => 1,
        );
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        $page = $this->page(array("table" => self::table, 'pageNum'=>1000,"where" => $where, "order" => "list asc"));
        static::rSet(self::$stid . self::page . 'interestsSql', $page['fullSql']);
        //获取表头
        $tr[] = array("科目编码", "科目名称", "方向", "期初金额", "借方累计", "贷方累计", "年初金额");
        $url = root . 'control/adIndex.html?cla=subject&fun=home&menu=interests';
        //获取记录
        foreach ($page['array'] as $array) {
            $res = $this->loopSubject($array, $url);
            $tr = array_merge($tr, $res);
        }
        //控件
        $button = $this->button($subjectType);
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='interestsForm' class='listPage'>" . space . $this->listTable(array("tr" => $tr, "showSort" => true)) . "</form>" .  clear;
        return json_encode($json, 320);
    }

    public function debt()
    {
        $json['html'] = $this->homeForm('负债');
        return json_encode($json, 320);
    }

    public function debtSearch()
    {
        $subjectType = '负债类';
        //like查询数组
        $like = array(
            "name" => $this->post('name'),
            "code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            'type' => $subjectType,
            'level' => 1,
        );
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        $page = $this->page(array("table" => self::table,'pageNum'=>1000, "where" => $where, "order" => "list asc"));
        static::rSet(self::$stid . self::page . 'debtSql', $page['fullSql']);
        $url = root . 'control/adIndex.html?cla=subject&fun=home&menu=debt';
        //获取表头
        $tr[] = array("科目编码", "科目名称", "方向", "期初金额", "借方累计", "贷方累计", "年初金额");
        //获取记录
        foreach ($page['array'] as $array) {
            $res = $this->loopSubject($array, $url);
            $tr = array_merge($tr, $res);
        }
        //控件
        $button = $this->button($subjectType);
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='debtForm' class='listPage'>" . space . $this->listTable(array("tr" => $tr, "showSort" => true)) . "</form>" .  clear;
        return json_encode($json, 320);
    }

    public function common(): bool|string
    {
        $json['html'] = $this->homeForm('共同');
        return json_encode($json, 320);
    }

    public function commonSearch(): bool|string
    {
        $subjectType = '共同类';
        //like查询数组
        $like = array(
            "name" => $this->post('name'),
            "code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            'type' => $subjectType,
            'level' => 1,
        );
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        $page = $this->page(array("table" => self::table,'pageNum'=>1000, "where" => $where, "order" => "list asc"));
        static::rSet(self::$stid . self::page . 'debtSql', $page['fullSql']);
        $url = root . 'control/adIndex.html?cla=subject&fun=home&menu=common';
        //获取表头
        $tr[] = array("科目编码", "科目名称", "方向", "期初金额", "借方累计", "贷方累计", "年初金额");
        //获取记录
        foreach ($page['array'] as $array) {
            $res = $this->loopSubject($array, $url);
            $tr = array_merge($tr, $res);
        }
        //控件
        $button = $this->button($subjectType);
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='commonForm' class='listPage'>" . space . $this->listTable(array("tr" => $tr, "showSort" => true)) . "</form>" .  clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $type = $this->get('type');
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } elseif (empty($type)) {
            $_SESSION['warn'] = '未找到类别';
        } else {
            $tr = [];

            $title = array("科目编码", "科目名称", "方向", "期初金额", "借方累计", "贷方累计", "年初金额");
            $result = find(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' order by code asc"));
            $this->isExport = true;
            foreach ($result['array'] as $array) {
                $res = $this->loopSubject($array, '');
                $tr = array_merge($tr, $res);
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, $type . self::title . ".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        } else {
            $exampleData = [];
            $all = find(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and level = 1 order by code asc"));
            foreach ($all['array'] as $array) {
                $res = $this->loopSubjectDown($array);
                $exampleData = array_merge($exampleData, $res);
            }
            $excel    = $this->excelHead();
            $fileName = '科目期初导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '科目编码'=>$example[0],
                            '科目名称'=>$example[1],
                            '方向'=>$example[2],
                            '辅助核算项'=>$example[3],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }


            $text = $this->control['name'] . "下载了科目期初导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入分析*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = '你还没有导入的权限';
        } elseif (static::total(array('table' => 'checkout', 'where' => "coid = '" . self::$coid . "'")) > 0) {
            $json['warn'] = '已存在结账，不能导入';
        }  else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $preSubject = [];
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $subject = query(self::table, "code = '$cell[科目编码]' and coid = '" . self::$coid . "'");
                    if (empty($preSubject) || $preSubject['id'] != $subject['id']) {
                        if (empty($subject['id'])) {
                            $text .= "第【{$row_list}】行：未找到科目</br>";
                        } elseif ($subject['assistAccount'] != $cell['辅助核算项']) {
                            $text .= "第【{$row_list}】行：科目辅助核算项和导入的辅助核算项不匹配</br>";
                        } else {
                            //删除所有的辅助核算
                            delete(array('table' => 'subject_assist', 'where' => "orderId = '$subject[id]'"));
                            $field = [
                                'initMoney' => self::yuanToCent($cell['期初余额'] ?: 0),
                                'borrowMoney' => self::yuanToCent($cell['借方累计'] ?: 0),
                                'loanMoney' => self::yuanToCent($cell['贷方累计'] ?: 0),
                            ];
                            if (preg_match(checkPrice, abs($field['initMoney'])) == 0) {
                                $text .= "第【{$row_list}】行：期初金额格式错误</br>";  // 多个规则提示最前面一条
                            } elseif (preg_match(checkPrice, abs($field['borrowMoney'])) == 0) {
                                $text .= "第【{$row_list}】行：借方累计格式错误</br>";  // 多个规则提示最前面一条
                            } elseif (preg_match(checkPrice, abs($field['loanMoney'])) == 0) {
                                $text .= "第【{$row_list}】行：贷方累计金额格式错误</br>";  // 多个规则提示最前面一条
                            } elseif ($subject['assistAccount'] == '否') {
                                $warn = static::update([
                                    "table" => self::table,
                                    "field" => $field,
                                    "where" => "id = '$subject[id]'"
                                ]);
                                if (in_array($warn, ["新增成功", "更新成功"])) {
                                    $this->loopMoney($subject['pid'], 'initMoney');
                                    $this->loopMoney($subject['pid'], 'borrowMoney');
                                    $this->loopMoney($subject['pid'], 'loanMoney');
                                    $x++;
                                    $text .= "第【{$row_list}】行导入成功<br>";
                                } else {
                                    $text .= "第【{$row_list}】行导入失败：编辑失败<br>";
                                }
                            }
                        }
                        $preSubject = $subject;
                    }

                    if ($subject['id'] && $cell['辅助核算项'] == '是') {
                        $warn = '';
                        $assistAccountIds = explode(',', $subject['assistAccountIds']);
                        $assitArr = explode('_', $cell['辅助核算编码']);
                        foreach ($assitArr as $code) {
                            $targetId = '';
                            foreach ($assistAccountIds as $aType) {
                                switch ($aType) {
                                    case '客户':
                                        $info = query('kehu', "coid = '" . self::$coid . "' and orderNo = '$code'");
                                        $targetId = $info['khid'];
                                        break;
                                    case '员工':
                                        $info = query('staff', "state !='离职' and orderNo = '$code'");
                                        $targetId = $info['stid'];
                                        break;
                                    case '供应商':
                                        $info = query('supplier', "coid = '" . self::$coid . "' and code = '$code'");
                                        $targetId = $info['id'];
                                        break;
                                    case '存货' :
                                        $info = query('material', "coid = '" . self::$coid . "' and barcode = '$code'");
                                        if (empty($info['id'])) {
                                            $info = query('material', "code = '$code' and coid = '" . self::$coid . "'");
                                        }
                                        $targetId = $info['id'];
                                        break;
                                    case '现金流':
                                        $info = query('cash', "coid = '" . self::$coid . "' and code = '$code'");
                                        $targetId = $info['id'];
                                        break;
                                    case '部门':
                                        $info = query('department', "orderNo = '$code'");
                                        $targetId = $info['id'];
                                        break;
                                    case '项目':
                                        $info = query('project', "coid = '" . self::$coid . "' and orderNo = '$code'");
                                        $targetId = $info['id'];
                                        break;
                                }
                                if ($targetId) {
                                    break;
                                }
                            }
                            if (empty($targetId)) {
                                $warn = "第【{$row_list}】行：未通过辅助核算编码找到辅助项</br>";
                                break;
                            }
                        }

                        if (empty($cell['辅助核算编码'])) {
                            $text .= "第【{$row_list}】行：未找到辅助核算编码</br>";
                        } elseif ($warn) {
                            $text .= $warn;
                        } else {

                            $assistField = [
                                'id' => suiji(),
                                'coid' => self::$coid,
                                'orderId' => $subject['id'],
                                'initMoney' => $cell['期初余额'],
                                'jieMoney' => $cell['借方累计'],
                                'daiMoney' => $cell['贷方累计'],
                                'initNum' => voucherEditClass::formatNum($cell['期初数量']),
                                'jieNum' => voucherEditClass::formatNum($cell['借方数量']),
                                'daiNum' => voucherEditClass::formatNum($cell['贷方数量']),
                            ];
                            $assistAccountIds = explode(',', $subject['assistAccountIds']);
                            $assitArr = explode('_', $cell['辅助核算编码']);
                            foreach ($assitArr as $code) {
                                $targetType = $targetId = '';
                                foreach ($assistAccountIds as $aType) {
                                    switch ($aType) {
                                        case '客户':
                                            $info = query('kehu', "coid = '" . self::$coid . "' and orderNo = '$code'");
                                            $targetId = $info['khid'];
                                            $targetType = 'khid';
                                            break;
                                        case '员工':
                                            $info = query('staff', "state !='离职' and orderNo = '$code'");
                                            $targetId = $info['stid'];
                                            $targetType = 'staffId';
                                            break;
                                        case '供应商':
                                            $info = query('supplier', "coid = '" . self::$coid . "' and code = '$code'");
                                            $targetId = $info['id'];
                                            $targetType = 'supplierId';
                                            break;
                                        case '存货' :
                                            $info = query('material', "coid = '" . self::$coid . "' and barcode = '$code'");
                                            if (empty($info['id'])) {
                                                $info = query('material', "code = '$code' and coid = '" . self::$coid . "'");
                                            }
                                            $targetId = $info['id'];
                                            $targetType = 'materialId';
                                            break;
                                        case '现金流':
                                            $info = query('cash', "coid = '" . self::$coid . "' and code = '$code'");
                                            $targetId = $info['id'];
                                            $targetType = 'cashId';
                                            break;
                                        case '部门':
                                            $info = query('department', "orderNo = '$code'");
                                            $targetId = $info['id'];
                                            $targetType = 'departmentId';
                                            break;
                                        case '项目':
                                            $info = query('project', "coid = '" . self::$coid . "' and orderNo = '$code'");
                                            $targetId = $info['id'];
                                            $targetType = 'projectId';
                                            break;
                                    }
                                    if ($targetId) {
                                        break;
                                    }
                                }
                                $assistField[$targetType] = $targetId;
                            }
                            $idCollection = array_filter([$assistField['khid']??'', $assistField['staffId']??'', $assistField['supplierId']??'', $assistField['projectId']??'', $assistField['materialId']??'', $assistField['departmentId']??'', $assistField['cashId']??'']);
                            asort($idCollection);
                            $assistField['idCollection'] =  implode(',', $idCollection);
                            $warn = static::insert([
                                "table" => 'subject_assist',
                                "field" => $assistField,
                            ]);

                            if ($warn == '新增成功') {
                                $x++;
                                $total = find(array('table' => 'subject_assist', 'single' => "orderId = '$subject[id]'", 'field' => "ifnull(sum(initMoney),0) as initMoney,ifnull(sum(jieMoney),0) as jieMoney,ifnull(sum(daiMoney),0) as daiMoney"));
                                $field['initMoney'] = self::yuanToCent($total['initMoney'] ?: 0);
                                $field['borrowMoney'] = self::yuanToCent($total['jieMoney'] ?: 0);
                                $field['loanMoney'] = self::yuanToCent($total['daiMoney'] ?: 0);
                                static::update([
                                    "table" => self::table,
                                    "field" => $field,
                                    "where" => "id = '$subject[id]'"
                                ]);
                                $this->loopMoney($subject['pid'], 'initMoney');
                                $this->loopMoney($subject['pid'], 'borrowMoney');
                                $this->loopMoney($subject['pid'], 'loanMoney');
                                $text .= "第【{$row_list}】行辅助核算导入成功<br>";
                            } else {
                                $text .= "第【{$row_list}】行导入失败：辅助核算编辑失败<br>";
                            }
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm,lossForm,costForm,interestsForm,debtForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }
    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'科目编码',
                    'aliasName'=>'科目编码',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'科目名称',
                    'aliasName'=>'科目名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'方向',
                    'aliasName'=>'方向',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'辅助核算项',
                    'aliasName'=>'辅助核算项(是/否)',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'辅助核算编码',
                    'aliasName'=>"辅助核算编码(用_串联多个辅助核算)",

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'辅助核算名称',
                    'aliasName'=>'辅助核算名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'期初余额',
                    'aliasName'=>'期初余额',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'期初数量',
                    'aliasName'=>'期初数量',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'借方数量',
                    'aliasName'=>'借方数量',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'借方累计',
                    'aliasName'=>'借方累计',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'贷方数量',
                    'aliasName'=>'贷方数量',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'贷方累计',
                    'aliasName'=>'贷方累计',

                    'isMust'=>false,
                ],
            ]
        };
    }

}

